using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class UIManager : MonoBehaviour
{
    [Header("游戏UI")]
    [SerializeField] private Text scoreText;
    [SerializeField] private Text comboText;
    [SerializeField] private Text livesText;
    [SerializeField] private Slider progressBar;
    
    [Header("面板")]
    [SerializeField] private GameObject pausePanel;
    [SerializeField] private GameObject gameOverPanel;
    [SerializeField] private GameObject victoryPanel;
    
    [Header("结算界面")]
    [SerializeField] private Text finalScoreText;
    [SerializeField] private Text highScoreText;
    [SerializeField] private Text rankText;
    
    [Header("动画")]
    [SerializeField] private Animator comboAnimator;
    [SerializeField] private GameObject perfectHitEffect;
    [SerializeField] private GameObject missEffect;
    
    private GameManager gameManager;
    private bool isPaused = false;
    
    private void Start()
    {
        gameManager = FindObjectOfType<GameManager>();
        
        // 确保所有面板初始隐藏
        if (pausePanel != null) pausePanel.SetActive(false);
        if (gameOverPanel != null) gameOverPanel.SetActive(false);
        if (victoryPanel != null) victoryPanel.SetActive(false);
        
        // 订阅事件
        Note.OnNoteHit += HandleNoteHit;
        Note.OnNoteMissed += HandleNoteMissed;
    }
    
    private void OnDestroy()
    {
        // 取消订阅事件
        Note.OnNoteHit -= HandleNoteHit;
        Note.OnNoteMissed -= HandleNoteMissed;
    }
    
    private void Update()
    {
        // 暂停功能
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            TogglePause();
        }
        
        // 更新进度条（如果有音乐）
        UpdateProgressBar();
    }
    
    // 更新分数显示
    public void UpdateScore(int score)
    {
        if (scoreText != null)
        {
            scoreText.text = "分数: " + score.ToString();
        }
    }
    
    // 更新连击显示
    public void UpdateCombo(int combo, int multiplier)
    {
        if (comboText != null)
        {
            comboText.text = combo.ToString() + "连击 x" + multiplier.ToString();
            
            // 触发连击动画
            if (comboAnimator != null && combo > 0 && combo % 10 == 0)
            {
                comboAnimator.SetTrigger("ComboMilestone");
            }
        }
    }
    
    // 更新生命值显示
    public void UpdateLives(int lives)
    {
        if (livesText != null)
        {
            livesText.text = "生命: " + lives.ToString();
        }
    }
    
    // 更新进度条
    private void UpdateProgressBar()
    {
        if (progressBar != null && gameManager != null)
        {
            AudioSource musicSource = gameManager.GetMusicSource();
            if (musicSource != null && musicSource.clip != null)
            {
                float progress = musicSource.time / musicSource.clip.length;
                progressBar.value = progress;
            }
        }
    }
    
    // 处理音符命中事件
    private void HandleNoteHit(int score, bool isPerfect)
    {
        if (isPerfect && perfectHitEffect != null)
        {
            // 显示完美命中特效
            StartCoroutine(ShowAndHideEffect(perfectHitEffect));
        }
    }
    
    // 处理音符错过事件
    private void HandleNoteMissed()
    {
        if (missEffect != null)
        {
            // 显示错过特效
            StartCoroutine(ShowAndHideEffect(missEffect));
        }
    }
    
    // 显示并隐藏特效的协程
    private IEnumerator ShowAndHideEffect(GameObject effect)
    {
        effect.SetActive(true);
        yield return new WaitForSeconds(0.5f);
        effect.SetActive(false);
    }
    
    // 显示游戏结束界面
    public void ShowGameOver(int finalScore, int highScore)
    {
        if (gameOverPanel != null)
        {
            gameOverPanel.SetActive(true);
            
            // 更新结算界面文本
            if (finalScoreText != null)
            {
                finalScoreText.text = "最终得分: " + finalScore.ToString();
            }
            
            if (highScoreText != null)
            {
                highScoreText.text = "最高分: " + highScore.ToString();
            }
            
            if (rankText != null)
            {
                // 根据分数计算等级
                string rank = CalculateRank(finalScore);
                rankText.text = "等级: " + rank;
            }
        }
    }
    
    // 显示胜利界面
    public void ShowVictory(int finalScore, int highScore)
    {
        if (victoryPanel != null)
        {
            victoryPanel.SetActive(true);
            
            // 更新结算界面文本
            if (finalScoreText != null)
            {
                finalScoreText.text = "最终得分: " + finalScore.ToString();
            }
            
            if (highScoreText != null)
            {
                highScoreText.text = "最高分: " + highScore.ToString();
            }
            
            if (rankText != null)
            {
                // 根据分数计算等级
                string rank = CalculateRank(finalScore);
                rankText.text = "等级: " + rank;
            }
        }
    }
    
    // 切换暂停状态
    public void TogglePause()
    {
        isPaused = !isPaused;
        
        if (pausePanel != null)
        {
            pausePanel.SetActive(isPaused);
        }
        
        // 暂停/恢复游戏
        Time.timeScale = isPaused ? 0f : 1f;
        
        // 暂停/恢复音乐
        if (gameManager != null)
        {
            AudioSource musicSource = gameManager.GetMusicSource();
            if (musicSource != null)
            {
                if (isPaused)
                {
                    musicSource.Pause();
                }
                else
                {
                    musicSource.UnPause();
                }
            }
        }
    }
    
    // 继续游戏按钮
    public void ResumeGame()
    {
        if (isPaused)
        {
            TogglePause();
        }
    }
    
    // 重新开始按钮
    public void RestartGame()
    {
        // 恢复正常时间流逝
        Time.timeScale = 1f;
        
        // 重新加载当前场景
        UnityEngine.SceneManagement.SceneManager.LoadScene(
            UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex);
    }
    
    // 返回主菜单按钮
    public void ReturnToMainMenu()
    {
        // 恢复正常时间流逝
        Time.timeScale = 1f;
        
        // 加载主菜单场景
        UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu");
    }
    
    // 退出游戏按钮
    public void QuitGame()
    {
        #if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
        #else
        Application.Quit();
        #endif
    }
    
    // 根据分数计算等级
    private string CalculateRank(int score)
    {
        if (score >= 10000) return "S+";
        if (score >= 8000) return "S";
        if (score >= 6000) return "A";
        if (score >= 4000) return "B";
        if (score >= 2000) return "C";
        return "D";
    }
}